package me.keiwu.pub.util.redis.config;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedisPool;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by kei on 12/09/2017.
 */
@Configuration
@ComponentScan({"me.keiwu.pub.util.redis"})
public class JedisConfiguration {

    @Value("${spring.redis.host}")
    private String host;
    @Value("${spring.redis.port}")
    private Integer port;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.pool.max-idle}")
    private Integer maxIdle;
    @Value("${spring.redis.pool.max-wait}")
    private Long maxWait;
    @Value("${spring.redis.pool.max-active}")
    private Integer maxActive;

    @Bean
    public ShardedJedisPool convertJedisPool() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(this.maxActive);
        jedisPoolConfig.setMaxIdle(this.maxIdle);
        jedisPoolConfig.setMaxWaitMillis(this.maxWait);
        List<JedisShardInfo> jedisShardInfoList = new ArrayList<>();
        JedisShardInfo info = new JedisShardInfo("redis://" + this.host + ":" + this.port);
        if (StringUtils.isNotBlank(this.password)) {
            info.setPassword(this.password);
        }
        jedisShardInfoList.add(info);
        return new ShardedJedisPool(jedisPoolConfig, jedisShardInfoList);
    }
}
